<?php

namespace app\admin\library;
// 添加Redis类的引用
use Redis;
use think\Config;
use think\Request;

class SchoolRedis
{

    protected $request;
    protected $config;
    protected $redis;

    public function __construct()
    {
        $this->request = Request::instance();
        $this->config = Config::get('redis');
    }
    /**
     * 生成缓存键
     */
    public function generateCacheKey($table_id, $search = '', $rel_type = null)
    {
        $key = "autoplan:list:{$table_id}";
        if (!empty($search)) {
            $key .= ":search:" . md5($search);
        }
        if ($rel_type !== null) {
            $key .= ":rel_type:{$rel_type}";
        }
        return $key;
    }

    /**
     * 获取Redis实例
     */
    public function getRedisInstance()
    {
        try {
            $redis = new Redis();
            // 获取Redis配置
            $config = config('cache.redis');
            $host = $config['host'] ?? '127.0.0.1';
            $port = $config['port'] ?? 6379;
            $timeout = $config['timeout'] ?? 0;
            $password = $config['password'] ?? '';
            $select = $config['select'] ?? 0;

            // 连接Redis
            if (!$redis->connect($host, $port, $timeout)) {
                return false;
            }

            // 验证密码
            if (!empty($password) && !$redis->auth($password)) {
                $redis->close();
                return false;
            }

            // 选择数据库
            if ($select > 0) {
                $redis->select($select);
            }

            return $redis;
        } catch (\Exception $e) {
            // 记录错误日志
            file_put_contents(
                $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/redis_error.log",
                date('Y-m-d H:i:s') . " - Redis连接失败: " . $e->getMessage() . "\n",
                FILE_APPEND
            );
            return false;
        }
    }

    /**
     * 从Redis获取缓存数据
     */
    public function getCacheData($cacheKey)
    {
        try {
            // 检查是否需要跳过缓存
            $skipCache = $this->request->param('skip_cache', 0);
            if ($skipCache) {
                return false;
            }

            $redis = $this->getRedisInstance();
            if ($redis === false) {
                return false;
            }

            // 获取缓存数据
            $cachedData = $redis->get($cacheKey);
            $redis->close();

            if ($cachedData !== false) {
                return json_decode($cachedData, true);
            }

            return false;
        } catch (\Exception $e) {
            // 记录错误日志
            file_put_contents(
                $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/redis_error.log",
                date('Y-m-d H:i:s') . " - 获取缓存失败: " . $e->getMessage() . "\n",
                FILE_APPEND
            );
            return false;
        }
    }

    /**
     * 设置Redis缓存数据
     */
    public function setCacheData($cacheKey, $data, $expire = 3600)
    {
        try {
            $redis = $this->getRedisInstance();
            if ($redis === false) {
                return false;
            }

            // 设置缓存数据
            $result = $redis->setex($cacheKey, $expire, json_encode($data));
            $redis->close();

            return $result;
        } catch (\Exception $e) {
            // 记录错误日志
            file_put_contents(
                $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/redis_error.log",
                date('Y-m-d H:i:s') . " - 设置缓存失败: " . $e->getMessage() . "\n",
                FILE_APPEND
            );
            return false;
        }
    }

    /**
     * 清除指定table_id的所有缓存
     */
    public function clearCacheByTableId($table_id)
    {
        try {
            $redis = $this->getRedisInstance();
            if ($redis === false) {
                return false;
            }

            // 清除该table_id的所有缓存键
            $pattern = "autoplan:list:{$table_id}*";
            $keys = $redis->keys($pattern);

            if (!empty($keys)) {
                $redis->del($keys);
            }

            $redis->close();
            return true;
        } catch (\Exception $e) {
            // 记录错误日志
            file_put_contents(
                $_SERVER["DOCUMENT_ROOT"] . "/../runtime/log/redis_error.log",
                date('Y-m-d H:i:s') . " - 清除缓存失败: " . $e->getMessage() . "\n",
                FILE_APPEND
            );
            return false;
        }
    }
}